package com.example.lynandroid.views

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import com.example.lynandroid.*
import com.example.lynandroid.enum.LifeType

class MyView(context: Context, val set: AttributeSet) : View(context, set) {
    private val paint = Paint()
    private var name: String? = null
    private var theId = 0

    init {
        paint.style = Paint.Style.FILL
        paint.isAntiAlias = true

        context.theme.obtainStyledAttributes(
            set,
            R.styleable.MyView,
            0, 0
        ).apply {

            try {
                name = getString(R.styleable.MyView_name)
                theId = getInt(R.styleable.MyView_id, 0)
            } finally {
                recycle()
            }
        }

        if (theId == 0) {
            paint.color = Color.RED
            // setOnClickListener { invalidate() }
        } else {
            paint.color = Color.BLUE
            setOnClickListener { requestLayout() }
        }
    }


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
//        log("widthSpec=${getMode(widthMeasureSpec)}")
//
//        log("heightSpec=${getMode(heightMeasureSpec)}")
//
//        log("given-width=${MeasureSpec.getSize(widthMeasureSpec)}")
//        log("given-height=${MeasureSpec.getSize(heightMeasureSpec)}")
//
//        log("screen-width=${screenWidth()}")
//        log("screen-width=${screenHeight()}")


        log(LifeType.Measure)
    }

    private fun getMode(measureSpec: Int): String {
        return when (MeasureSpec.getMode(measureSpec)) {
            MeasureSpec.AT_MOST -> "AT_MOST"
            MeasureSpec.EXACTLY -> "EXACTLY"
            MeasureSpec.UNSPECIFIED -> "UNSPECIFIED"
            else -> "NONE"
        }
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
        log(LifeType.Layout)
        width
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        log(LifeType.Draw)
        canvas?.drawRoundRect(0f, 0f, 500f, 100f, 20f, 20f, paint)
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        log(LifeType.AttachToWindow)
    }

    override fun onWindowFocusChanged(hasWindowFocus: Boolean) {
        super.onWindowFocusChanged(hasWindowFocus)
        log(LifeType.WindowFocusChange)
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        log(LifeType.DetachFromWindow)
    }

    override fun onVisibilityChanged(changedView: View, visibility: Int) {
        super.onVisibilityChanged(changedView, visibility)
        log(LifeType.VisibleChange)
    }


    private fun log(lifeType: LifeType) {
        lifeLog(name, lifeType)
    }
}